#include "JumpAnimation.h"
#include "CheckersPiece.h"
#include "CheckersBoard.h"
#include "CheckersApp.h"

// Constants
const float JumpAnimation::g = 9.81f;

JumpAnimation::JumpAnimation(CheckersApp *app, CheckersPiece *piece):
	app(app),
	piece(piece)
{
}

void JumpAnimation::MoveToSquare(CheckersBoard *board, int i, int j)
{
	// First translate onto correct position in board local space, then apply board world transform
	DirectX::XMMATRIX worldMatrix = DirectX::XMMatrixMultiply(
		DirectX::XMMatrixTranslation(-3.5f + 1.0f*j, 0.1f, -3.5f + 1.0f*i),
		board->WorldMatrix());

	// Compute destination
	destination = DirectX::XMVector3Transform(DirectX::XMVectorZero(), worldMatrix);
}

void JumpAnimation::Start()
{
	// Compute initial velocity... basic physics!
	DirectX::XMVECTOR deltaPos = DirectX::XMVectorSubtract(destination, piece->Position());
	DirectX::XMFLOAT3 v0(DirectX::XMVectorGetX(deltaPos) / interval, g * interval / 2.0f, DirectX::XMVectorGetZ(deltaPos) / interval);
	velocity = DirectX::XMLoadFloat3(&v0);

	// Acceleration is just -g in y-direction
	DirectX::XMFLOAT3 a(0.0f, -g, 0.0f);
	acceleration = DirectX::XMLoadFloat3(&a);
}

void JumpAnimation::Tick()
{
	// Add velocity vector scaled by delta time to the piece's position
	piece->Translate(DirectX::XMVectorScale(velocity, app->DeltaTime()));

	// Compute new velocity from acceleration... it's physics!
	velocity = DirectX::XMVectorAdd(
		velocity,
		DirectX::XMVectorScale(acceleration, app->DeltaTime()));

	// Compute vector pointing from current position to destination
	DirectX::XMVECTOR p = DirectX::XMVectorSubtract(destination, piece->Position());

	// If p and velocity have a negative dot product, we are past the destination
	if (DirectX::XMVectorGetX(DirectX::XMVector3Dot(p, velocity)) <= 0.0f)
	{
		piece->Translate(p);
		done = true;
	}
}